<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    
    <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="./abi.js"></script>
    <script src="./web3.min.js"></script>

</head>


<h1 id="showres">显示数据</h1>
<body>
 <input type="text" class="set-data" maxlength="9" 
 onkeyup="this.value=this.value.replace(/\D/g,'')"
 onafterpaste="this.value=this.value.replace(/\D/g,'')"> 
 <button id="savedata">保存数据</button>
 <h3 id="txStatus"></h3>

    <script>
      var demoContract;
      var userAccount;

      $("#savedata").click(function(){
          var num = $(".set-data").val();
          console.log(num)
          if(num){
            saveData(num)
          }
          
      })

      function startApp() {
        var contractAddress = "0xe72dd631b0a9202c59f9cdb9233777d702a1c01b";
        demoContract = web3.eth.contract(ABI).at(contractAddress);

        console.log('demoContract',demoContract)
        var accountInterval = setInterval(function() {
          // Check if account has changed
          if (web3.eth.accounts[0] !== userAccount) {
            userAccount = web3.eth.accounts[0];
            
            console.log(userAccount)

            showData(userAccount)
          }
        }, 100);

        // Start here
      }

      function showData(userAccount){
       var r =  demoContract.getData(function(err,result){
            console.log(result.toString())
            if(err){

            }else{
                $("#showres").html(result.toString())
                $("#txStatus").text("");
            }
        })
       
      }

      function saveData(num){
        $("#txStatus").text("正在保存数据，请稍等。。。");
        demoContract.setData(num,function(err,res){
            if(err){

            }else{
                console.log(demoContract.events)
                var events = demoContract.allEvents();
                events.watch(function(error, result){
                    if(!err)
                        console.log(result)
                        showData()
                });
 
            }
           
        })
      }
              
        window.addEventListener('load', function() {

        // 检查web3是否已经注入到(Mist/MetaMask)
        if (typeof web3 !== 'undefined') {
        // 使用 Mist/MetaMask 的提供者
        web3js = new Web3(web3.currentProvider);
        } else {
        // 处理用户没安装的情况， 比如显示一个消息
        // 告诉他们要安装 MetaMask 来使用我们的应用
            alert("请先安装Metamask插件")
        }

        console.log(web3.eth.accounts)
        // 现在你可以启动你的应用并自由访问 Web3.js:
        startApp()

        })

    </script>
</body>
</html>